package com.ktjiaoyu.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktjiaoyu.server.config.security.JwtTokenUtil;
import com.ktjiaoyu.server.mapper.AdminMapper;
import com.ktjiaoyu.server.mapper.RoleMapper;
import com.ktjiaoyu.server.pojo.Admin;
import com.ktjiaoyu.server.pojo.AdminLoginParam;
import com.ktjiaoyu.server.pojo.RespBean;
import com.ktjiaoyu.server.pojo.Role;
import com.ktjiaoyu.server.service.IAdminService;
import com.ktjiaoyu.server.service.impl.UserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jjx
 * @since 2024-01-23
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Resource
    private AdminMapper adminMapper;
    @Resource
    UserDetailServiceImpl userDetailService;
    @Resource
    PasswordEncoder passwordEncoder;
    @Resource
    RoleMapper roleMapper;

    @Resource
    JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;


    @Override
    public RespBean login(AdminLoginParam adminLoginParam, HttpServletRequest request) {
        //验证验证码
        String captcha = (String)request.getSession()
                .getAttribute("captcha");
        if(StringUtils.isEmpty(adminLoginParam.getCode())||
                !captcha.equalsIgnoreCase(adminLoginParam.getCode())){
            return RespBean.error("验证码输入错误，请重新输入！");
        }

        //根据用户名查询用户
        Admin admin =null;
        try {
            admin = (Admin)userDetailService.loadUserByUsername(adminLoginParam.getUsername());
        }catch(UsernameNotFoundException e) {
            return RespBean.error(e.getMessage());
        }

        if(admin==null || passwordEncoder.matches(adminLoginParam.getPassword(),
                admin.getPassword())){
            return RespBean.error("用户名或者密码错误");
        }
        if(!admin.getState()){
            return RespBean.error("账号被冻结");
        }
        //先要在springsecurity里面进行登录
        UsernamePasswordAuthenticationToken authenticationToken
                =new UsernamePasswordAuthenticationToken(admin,null,admin.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //生成token
        String token = jwtTokenUtil.genegrateToken(admin);

        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        map.put("tokenHead",tokenHead);
        
        //响应前端
        return RespBean.success("登录成功",map);
    }

    @Override
    public Admin getAdminByUserName(String username) {
        // 按用户名查询，并且enabled为true，表示当前用户是启用状态
        QueryWrapper<Admin> qw=new QueryWrapper<Admin>();
        qw.eq("username",username);
        qw.eq("state",1);
        return adminMapper.selectOne(qw); // 需要注意的是t_admin表的enabled列名修改为state了
    }

    @Override
    public IPage<Admin> selectByPage(Page<Admin> page, String query, String sort) {
        //组装过滤条件
        QueryWrapper<Admin> qw=new QueryWrapper<>();
        qw.like("name",query).or().like("phone",query);

        //排序
        if(sort.equals("+id")){
            qw.orderByAsc("id");
        }else{
            qw.orderByDesc("id");
        }

        //调用分页查询方法
        Page<Admin> adminPage = adminMapper.selectPage(page, qw);
        //返回分页数据
        return adminPage;
    }

    @Override
    public boolean saveAdmin(Admin admin) {
        return adminMapper.insert(admin)>0?true:false;
    }

    @Override
    public boolean updateAdmin(Admin admin) {
        return adminMapper.updateById(admin)>0?true:false;
    }

    @Override
    public List<Role> findRolesAndMenusByAdminId(Integer adminId) {
        List<Role> roles = adminMapper.findRolesByAdminId(adminId).stream().map((role) -> {
            //将角色下的权限查询出来
            role.setChildren(roleMapper.findMenuByRole(role.getId()));
            return role;
        }).collect(Collectors.toList());
        return roles;
    }

    // 通过操作员用户ID查询其拥有的角色列表
    @Override
    public List<Role> findRolesByAdminId(Integer adminId) {
        return adminMapper.findRolesByAdminId(adminId);
    }

    // 通过操作员用户ID查询其拥有菜单URL集合
    @Override
    public List<String> findMenuUrlByAdminId(Integer adminId) {
        return adminMapper.findMenuUrlByAdminId(adminId);
    }

}
